
import { message } from 'antd';
class MMUtil{
	request(param){
		return new Promise((resolve,reject)=>{
			$.ajax({
				type     :param.method     || 'get',
				url      :param.url      || '',
				async    :param.async     ||  true,
				dataType :param.type || 'json',
				data     :param.data     ||  null,
				success   :(res)=>{
					if(res.statusCode ===0){
						typeof resolve === 'function' && resolve(res.content,res.message);
					}else if(res.statusCode ===403){
						res.content.code = 403 
						typeof resolve === 'function' && resolve(res.content);
					}else if(res.statusCode ===304){
						this.doLogin();
					}else{
						typeof reject === 'function' && reject(res.message || res.content);
					}
				},
				error(err){
					typeof reject === 'function' && reject(err.message);
				}
			})
		});
	}
	doLogin(){
		//window.location.href='/login?redirect='+encodeURIComponent(window.location.pathname);
		window.location.href='/#/login';
	}
	//获取url参数
	getUrlParam(name){
		let queryString=window.location.search.split('?')[1] || '',
				reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)"),
				result = queryString.match(reg);
		return result?decodeURIComponent(result[2]):null;

	}
	//错误提示
	errorTips(errMsg){
		message.error(errMsg || '出问题');
		return false;
	}
	// 向本地存储里放数据
  setStorage(name, data){
      // array / json
      if(typeof data === 'object'){
          let jsonString = JSON.stringify(data);
          window.localStorage.setItem(name, jsonString);
      }
      // number / string / boolean
      else if(['number','string','boolean'].indexOf(typeof data)>=0){
          window.localStorage.setItem(name, data);
      }
      // undefined / function
      else{
          message.error('该数据类型不能用于本地存储');
      }
  }
  // 从本地存储获取数据
  getStorage(name){
      let data = window.localStorage.getItem(name);
      if(data){
          return data;
      }else{
          return '';
      }
  }
  // 删除本地存储
  removeStorage(name){
      window.localStorage.removeItem(name);
  }
}
export default MMUtil;